package com.tarena.test.rabbitmq.dead;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import org.junit.Before;
import org.junit.Test;

public class DeadLetterMode {
    //业务交换机
    public static final String BUSINESS_EX="business-exchange";
    //业务队列
    public static final String BUSINESS_QUEUE="business-queue";
    //业务路由key
    public static final String BUSINESS_ROUTING_KEY="business";
    //死信交换机
    public static final String DEAD_LETTER_EX="dead-letter-exchange";
    //死信队列
    public static final String DEAD_LETTER_QUEUE="dead-letter-queue";
    //死信路由key
    public static final String DEAD_LETTER_ROUTING_KEY="dead-letter-routing-key";
    private Channel channel;
    @Before
    public void initChannel() throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection= factory.newConnection();
        channel=connection.createChannel();
    }
    //声明组件 绑定
    @Test
    public void declareComponent() throws IOException {
        //声明业务交换机
        channel.exchangeDeclare(BUSINESS_EX, "direct");
        //声明业务队列时,需要绑定的死信交换机和死信队列的属性map
        Map<String, Object> args=new HashMap<>();
        args.put("x-dead-letter-exchange", DEAD_LETTER_EX);
        args.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        //为了验证死信队列的作用 我们通过TTL 设置消息超时 来产生死信 同时也是延迟消息的逻辑
        args.put("x-message-ttl", 10000);
        //声明业务队列
        channel.queueDeclare(BUSINESS_QUEUE, false, false, false, args);
        //绑定业务队列到交换机
        channel.queueBind(BUSINESS_QUEUE, BUSINESS_EX, BUSINESS_ROUTING_KEY);
        //声明死信交换机
        channel.exchangeDeclare(DEAD_LETTER_EX, "direct");
        //声明死信队列
        channel.queueDeclare(DEAD_LETTER_QUEUE, false, false, false, null);
        //绑定
        channel.queueBind(DEAD_LETTER_QUEUE, DEAD_LETTER_EX, DEAD_LETTER_ROUTING_KEY);
    }

    @Test
    public void sendMessage() throws IOException {
        System.out.println("生产者即将发送");
        //1.准备一个发送的消息数据
        String msg="这是一条死信消息";
        channel.basicPublish(BUSINESS_EX,"business",null,msg.getBytes());
        System.out.println("生产者发送结束");
    }
}
